<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 动态标题：练习模式 vs 正式闯关 -->
  <title th:text="${isPractice ? '练习模式 - 渐进学习平台' : '正式闯关 - 渐进学习平台'}">知识闯关</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    /* ===== 基础样式 ===== */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* 动态主题色：练习模式绿色系，正式闯关红色系 */
    body {
      color: #333;
      min-height: 100vh;
      padding: 20px;
      transition: all 0.3s ease;
    }

    /* 练习模式背景色 */
    body.practice-mode {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    /* 正式闯关背景色 */
    body.formal-mode {
      background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
    }

    /* ===== 导航栏样式 ===== */
    .navbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: rgba(255, 255, 255, 0.95);
      padding: 15px 30px;
      border-radius: 12px;
      margin-bottom: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .nav-brand {
      font-size: 24px;
      font-weight: bold;
      color: #764ba2;
      display: flex;
      align-items: center;
    }

    .nav-brand i {
      margin-right: 10px;
      font-size: 26px;
    }

    .nav-buttons {
      display: flex;
      gap: 15px;
    }

    /* ===== 按钮样式 ===== */
    .btn {
      padding: 10px 20px;
      border-radius: 8px;
      text-decoration: none;
      font-weight: 600;
      transition: all 0.3s;
      display: inline-flex;
      align-items: center;
      cursor: pointer;
      border: none;
    }

    .btn-outline {
      border: 2px solid #764ba2;
      color: #764ba2;
      background: transparent;
    }

    .btn-primary {
      background: linear-gradient(135deg, #007bff, #0056b3);
      color: white;
      box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
    }

    .btn-success {
      background: linear-gradient(135deg, #28a745, #20c997);
      color: white;
      box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }

    .btn-warning {
      background: linear-gradient(135deg, #ffc107, #fd7e14);
      color: white;
      box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3);
    }

    .btn-danger {
      background: linear-gradient(135deg, #dc3545, #e83e8c);
      color: white;
      box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
    }

    .btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
    }

    .btn-outline:hover {
      background: #764ba2;
      color: white;
    }

    /* ===== 主要内容区域 ===== */
    .main-content {
      background: white;
      border-radius: 15px;
      padding: 40px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
      margin-bottom: 30px;
    }

    .welcome-section {
      text-align: center;
      margin-bottom: 40px;
    }

    .welcome-title {
      font-size: 36px;
      color: #333;
      margin-bottom: 15px;
    }

    .welcome-subtitle {
      font-size: 18px;
      color: #666;
      max-width: 600px;
      margin: 0 auto 30px;
      line-height: 1.6;
    }

    /* ===== 模式指示器 ===== */
    .mode-indicator {
      display: inline-block;
      padding: 8px 20px;
      border-radius: 20px;
      font-weight: bold;
      margin-bottom: 20px;
      font-size: 16px;
    }

    .practice-mode .mode-indicator {
      background: #e8f5e8;
      color: #4CAF50;
    }

    .formal-mode .mode-indicator {
      background: #ffebee;
      color: #f44336;
    }

    /* ===== 当前知识点信息 ===== */
    .current-point-info {
      border-radius: 12px;
      padding: 25px;
      margin-bottom: 30px;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
      color: white;
    }

    /* 练习模式知识点信息样式 */
    .practice-mode .current-point-info {
      background: linear-gradient(135deg, #28a745, #20c997);
    }

    /* 正式闯关知识点信息样式 */
    .formal-mode .current-point-info {
      background: linear-gradient(135deg, #dc3545, #e83e8c);
    }

    .point-details h2 {
      font-size: 28px;
      margin-bottom: 10px;
    }

    .point-meta {
      display: flex;
      gap: 20px;
      font-size: 14px;
      opacity: 0.9;
    }

    /* ===== 答题区域 ===== */
    .quiz-container {
      background: white;
      border-radius: 12px;
      padding: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      margin-bottom: 30px;
    }

    .quiz-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #e9ecef;
    }

    .quiz-title {
      font-size: 24px;
      color: #333;
    }

    .quiz-stats {
      display: flex;
      gap: 20px;
      font-size: 16px;
    }

    .stat-item {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .stat-value {
      font-weight: bold;
      color: #007bff;
    }

    /* ===== 倒计时样式 ===== */
    .countdown {
      font-size: 24px;
      font-weight: bold;
      color: #dc3545;
      padding: 10px 20px;
      background: rgba(220, 53, 69, 0.1);
      border-radius: 8px;
      border: 2px solid #dc3545;
    }

    /* ===== 题目样式 ===== */
    .question-container {
      margin-bottom: 30px;
    }

    .question-text {
      font-size: 20px;
      margin-bottom: 20px;
      line-height: 1.6;
    }

    /* 单选题和多选题样式 */
    .options-container {
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-bottom: 30px;
    }

    .option-item {
      padding: 15px 20px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;
      display: flex;
      align-items: center;
    }

    .option-item:hover {
      border-color: #007bff;
      background: rgba(0, 123, 255, 0.05);
    }

    .option-item.selected {
      border-color: #007bff;
      background: rgba(0, 123, 255, 0.1);
    }

    .option-item.correct {
      border-color: #28a745;
      background: rgba(40, 167, 69, 0.1);
    }

    .option-item.incorrect {
      border-color: #dc3545;
      background: rgba(220, 53, 69, 0.1);
    }

    .option-label {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #e9ecef;
      border-radius: 50%;
      margin-right: 15px;
      font-weight: bold;
    }

    .option-item.selected .option-label {
      background: #007bff;
      color: white;
    }

    .option-item.correct .option-label {
      background: #28a745;
      color: white;
    }

    .option-item.incorrect .option-label {
      background: #dc3545;
      color: white;
    }

    /* 填空题样式 */
    .fill-blank-input {
      width: 100%;
      padding: 15px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      font-size: 16px;
      margin-bottom: 20px;
    }

    .fill-blank-input:focus {
      border-color: #007bff;
      outline: none;
    }

    /* 代码题样式 */
    .code-editor {
      width: 100%;
      min-height: 200px;
      padding: 15px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      font-family: 'Courier New', monospace;
      font-size: 14px;
      margin-bottom: 20px;
      resize: vertical;
    }

    .code-editor:focus {
      border-color: #007bff;
      outline: none;
    }

    /* 简答题样式 */
    .essay-textarea {
      width: 100%;
      min-height: 150px;
      padding: 15px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      font-size: 16px;
      margin-bottom: 20px;
      resize: vertical;
    }

    .essay-textarea:focus {
      border-color: #007bff;
      outline: none;
    }

    /* 解析区域样式 */
    .explanation-container {
      margin-top: 30px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
      border-left: 4px solid #007bff;
      display: none;
    }

    .explanation-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #007bff;
    }

    /* ===== 进度控制 ===== */
    .progress-controls {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 30px;
    }

    .progress-buttons {
      display: flex;
      gap: 15px;
    }

    .progress-bar {
      flex-grow: 1;
      height: 8px;
      background: #e9ecef;
      border-radius: 4px;
      margin: 0 20px;
      overflow: hidden;
    }

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #28a745, #20c997);
      border-radius: 4px;
      transition: width 0.3s;
    }

    /* ===== 结果统计区域 ===== */
    .results-container {
      background: white;
      border-radius: 12px;
      padding: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      margin-bottom: 30px;
      display: none;
    }

    .results-title {
      font-size: 28px;
      text-align: center;
      margin-bottom: 30px;
      color: #333;
    }

    .results-stats {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }

    .result-stat {
      text-align: center;
      padding: 20px;
      border-radius: 8px;
      background: #f8f9fa;
    }

    .result-value {
      font-size: 36px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .result-label {
      font-size: 16px;
      color: #666;
    }

    .result-stat.score .result-value {
      color: #007bff;
    }

    .result-stat.correct .result-value {
      color: #28a745;
    }

    .result-stat.time .result-value {
      color: #fd7e14;
    }

    .result-stat.rank .result-value {
      color: #6f42c1;
    }

    /* ===== 经验成长区域 ===== */
    .experience-container {
      background: white;
      border-radius: 12px;
      padding: 30px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      margin-bottom: 30px;
    }

    .experience-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .experience-title {
      font-size: 24px;
      color: #333;
    }

    .experience-level {
      font-size: 18px;
      font-weight: bold;
      color: #007bff;
    }

    .experience-bar {
      height: 20px;
      background: #e9ecef;
      border-radius: 10px;
      margin-bottom: 10px;
      overflow: hidden;
    }

    .experience-fill {
      height: 100%;
      background: linear-gradient(90deg, #ffc107, #fd7e14);
      border-radius: 10px;
      transition: width 0.5s;
    }

    .experience-info {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #666;
    }

    /* ===== 图表容器 ===== */
    .charts-container {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }

    .chart-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .chart-title {
      font-size: 18px;
      margin-bottom: 15px;
      text-align: center;
      color: #333;
    }

    /* ===== 响应式设计 ===== */
    @media (max-width: 768px) {
      .nav-buttons {
        flex-direction: column;
        width: 100%;
        gap: 10px;
      }

      .navbar {
        flex-direction: column;
        gap: 15px;
      }

      .quiz-header {
        flex-direction: column;
        gap: 15px;
      }

      .progress-controls {
        flex-direction: column;
        gap: 15px;
      }

      .progress-bar {
        width: 100%;
        margin: 10px 0;
      }

      .results-stats {
        grid-template-columns: 1fr 1fr;
      }

      .charts-container {
        grid-template-columns: 1fr;
      }
    }

    @media (max-width: 480px) {
      .main-content {
        padding: 20px 15px;
      }

      .point-meta {
        flex-direction: column;
        gap: 10px;
      }

      .results-stats {
        grid-template-columns: 1fr;
      }
    }

    /* ===== 加载状态 ===== */
    .loading-container {
      text-align: center;
      padding: 40px;
    }

    .loading-spinner {
      width: 50px;
      height: 50px;
      border: 5px solid #f3f3f3;
      border-top: 5px solid #007bff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 20px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .error-container {
      text-align: center;
      padding: 40px;
    }

    .error-icon {
      font-size: 48px;
      margin-bottom: 20px;
      color: #dc3545;
    }
  </style>
</head>
<!-- 根据模式动态设置body类，实现不同主题 -->
<body th:classappend="${isPractice ? 'practice-mode' : 'formal-mode'}">
<div class="container">
  <!-- 导航栏 -->
  <nav class="navbar">
    <div class="nav-brand">
      <i>🚀</i> 渐进学习平台
    </div>
    <div class="nav-buttons">
      <!-- 返回按钮：练习模式返回准备页，正式闯关返回准备页 -->
      <a th:href="@{/practice/gateway/prepare(pointId=${pointId})}" class="btn btn-outline">
        <i class="fas fa-arrow-left"></i> 返回准备页
      </a>
      <a th:href="@{/knowledge/gym}" class="btn btn-outline">
        <i class="fas fa-home"></i> 返回训练馆
      </a>
    </div>
  </nav>

  <!-- 主要内容区域 -->
  <div class="main-content">
    <div class="welcome-section">
      <!-- 动态标题：根据模式显示不同标题 -->
      <h1 class="welcome-title" th:text="${isPractice ? '📚 练习模式' : '⚡ 正式闯关'}">知识闯关</h1>
      <!-- 动态副标题：根据模式显示不同描述 -->
      <p class="welcome-subtitle" th:text="${isPractice ? '不限时练习，巩固知识点' : '限时挑战，检验掌握程度'}">模式描述</p>
      <!-- 模式指示器 -->
      <div class="mode-indicator" th:text="${isPractice ? '练习模式' : '闯关模式'}">模式指示器</div>
    </div>

    <!-- 修改知识点信息部分，直接使用Thymeleaf渲染 -->
    <div class="current-point-info">
      <div class="point-details">
        <h2 th:text="${point?.title}">知识点标题</h2>
        <div class="point-meta">
          <span>难度: <strong th:text="${point?.difficultyLevel}">初级</strong></span>
          <span>预计时间: <strong th:text="${point?.baseDuration}">15分钟</strong></span>
          <span>经验值: <strong th:text="${point?.baseExperience}">100</strong></span>
          <span>类型: <strong th:text="${point?.knowledgeType}">概念理解型</strong></span>
        </div>
      </div>
    </div>

    <!-- 答题区域 -->
    <div class="quiz-container" id="quiz-container">
      <!-- 加载状态 -->
      <div class="loading-container" id="loadingContainer">
        <div class="loading-spinner"></div>
        <h3>加载题目中...</h3>
        <p>请稍候，正在获取题目数据</p>
      </div>

      <!-- 错误状态 -->
      <div class="error-container" id="errorContainer" style="display: none;">
        <div class="error-icon">⚠️</div>
        <h3 id="errorTitle">加载失败</h3>
        <p id="errorMessage">无法加载题目数据，请稍后重试</p>
        <button class="btn btn-primary" id="retryBtn">重新加载</button>
      </div>

      <!-- 答题界面 -->
      <div id="quizContent" style="display: none;">
        <div class="quiz-header">
          <!-- 动态标题：根据模式显示不同标题 -->
          <div class="quiz-title" th:text="${isPractice ? '练习模式 - 不限时学习' : '闯关模式 - 限时挑战'}">模式标题</div>
          <div class="quiz-stats">
            <div class="stat-item">
              <i class="fas fa-question-circle"></i>
              <span>题目: <span class="stat-value" id="currentQuestion">1</span>/<span id="totalQuestions">0</span></span>
            </div>
            <div class="stat-item">
              <i class="fas fa-check-circle"></i>
              <span>正确: <span class="stat-value" id="correctAnswers">0</span></span>
            </div>
            <!-- 计时器：只在正式闯关模式显示 -->
            <div class="stat-item" th:if="${not isPractice}" id="timerContainer">
              <i class="fas fa-clock"></i>
              <span>剩余时间: <span class="countdown" id="countdown">15:00</span></span>
            </div>
          </div>
        </div>

        <div class="question-container">
          <div class="question-text" id="questionText">
            加载题目中...
          </div>
          <div id="answerContainer">
            <!-- 答案区域会根据题目类型动态生成 -->
          </div>
        </div>

        <!-- 解析区域：练习模式显示，正式闯关不显示 -->
        <div class="explanation-container" th:if="${isPractice}" id="explanationContainer">
          <div class="explanation-title">解析</div>
          <div id="explanationText">解析内容将在这里显示</div>
        </div>

        <div class="progress-controls">
          <div class="progress-buttons">
            <button class="btn btn-outline" id="prevBtn">
              <i class="fas fa-arrow-left"></i> 上一题
            </button>
            <!-- 检查答案按钮：只在练习模式显示 -->
            <button class="btn btn-primary" th:if="${isPractice}" id="checkBtn">
              <i class="fas fa-check"></i> 检查答案
            </button>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" id="progressFill" style="width: 0%"></div>
          </div>
          <div class="progress-buttons">
            <button class="btn btn-success" id="nextBtn">
              下一题 <i class="fas fa-arrow-right"></i>
            </button>
            <!-- 提交按钮：只在正式闯关模式显示 -->
            <button class="btn btn-danger" th:if="${not isPractice}" id="submitBtn">
              <i class="fas fa-paper-plane"></i> 提交闯关
            </button>
            <!-- 完成练习按钮：只在练习模式显示 -->
            <button class="btn btn-warning" th:if="${isPractice}" id="completePracticeBtn">
              <i class="fas fa-flag-checkered"></i> 完成练习
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 结果统计区域 -->
    <div class="results-container" id="resultsContainer">
      <h2 class="results-title" id="resultsTitle">练习完成</h2>
      <div class="results-stats">
        <div class="result-stat score">
          <div class="result-value" id="finalScore">0</div>
          <div class="result-label">得分</div>
        </div>
        <div class="result-stat correct">
          <div class="result-value" id="finalCorrect">0</div>
          <div class="result-label">正确题目</div>
        </div>
        <!-- 用时统计：只在正式闯关模式显示 -->
        <div class="result-stat time" th:if="${not isPractice}" id="timeStat">
          <div class="result-value" id="finalTime">00:00</div>
          <div class="result-label">用时</div>
        </div>
        <!-- 排位统计：只在正式闯关模式显示 -->
        <div class="result-stat rank" th:if="${not isPractice}" id="rankStat">
          <div class="result-value" id="finalRank">-</div>
          <div class="result-label">排位</div>
        </div>
      </div>
      <div style="text-align: center; margin-top: 20px;">
        <!-- 查看解析按钮：练习模式显示，正式闯关不显示 -->
        <button class="btn btn-primary" th:if="${isPractice}" id="reviewBtn">
          <i class="fas fa-redo"></i> 查看解析
        </button>
        <!-- 下一个知识点按钮：练习模式进入正式闯关，正式闯关进入下一个知识点 -->
        <button class="btn btn-success" id="nextPointBtn">
          <span th:text="${isPractice ? '开始闯关' : '下一个知识点'}">下一个知识点</span> <i class="fas fa-arrow-right"></i>
        </button>
      </div>
    </div>

    <!-- 经验成长区域：只在正式闯关模式显示 -->
    <div class="experience-container" th:if="${not isPractice}" id="experienceContainer" style="display: none;">
      <div class="experience-header">
        <div class="experience-title">成长进度</div>
        <div class="experience-level">等级: <span id="userLevel">-</span></div>
      </div>
      <div class="experience-bar">
        <div class="experience-fill" id="experienceFill" style="width: 0%"></div>
      </div>
      <div class="experience-info">
        <span>当前经验: <span id="currentExp">0</span></span>
        <span>升级所需: <span id="nextLevelExp">0</span></span>
      </div>
    </div>

    <!-- 图表容器：只在正式闯关模式显示 -->
    <div class="charts-container" th:if="${not isPractice}" id="chartsContainer" style="display: none;">
      <div class="chart-card">
        <div class="chart-title">知识点掌握情况</div>
        <canvas id="masteryChart"></canvas>
      </div>
      <div class="chart-card">
        <div class="chart-title">训练次数统计</div>
        <canvas id="trainingChart"></canvas>
      </div>
    </div>
  </div>
</div>

<script th:inline="javascript">
  // ===== 初始化数据 =====
  // 从Thymeleaf获取后端传递的数据
  const isPractice = /*[[${isPractice}]]*/ false;
  const sessionId = /*[[${sessionId}]]*/ null;
  const pointId = /*[[${pointId}]]*/ null;

  // 关键修改：直接从Thymeleaf获取题目数据
  const questions = /*[[${questions}]]*/ [];
  const pointInfo = /*[[${point}]]*/ {};

  console.log("从后端获取的题目数据:", questions);
  console.log("从后端获取的知识点信息:", pointInfo);

  // 当前状态
  let currentState = {
    mode: isPractice ? 'practice' : 'formal',
    currentQuestion: 0,
    userAnswers: [],
    checked: false,
    timeLeft: 15 * 60, // 15分钟，以秒为单位
    timer: null,
    startTime: null,
    completed: false,
    quizData: {
      questions: questions || [], // 直接使用从Thymeleaf获取的题目数据
      pointInfo: pointInfo || {}
    },
    userData: {
      level: 0,
      currentExp: 0,
      nextLevelExp: 0,
      practiceCount: 0,
      challengeCount: 0,
      averageScore: 0,
      mastery: {}
    }
  };

  // DOM元素
  const loadingContainer = document.getElementById('loadingContainer');
  const errorContainer = document.getElementById('errorContainer');
  const quizContent = document.getElementById('quizContent');
  const errorTitle = document.getElementById('errorTitle');
  const errorMessage = document.getElementById('errorMessage');
  const retryBtn = document.getElementById('retryBtn');
  const currentQuestion = document.getElementById('currentQuestion');
  const totalQuestions = document.getElementById('totalQuestions');
  const correctAnswers = document.getElementById('correctAnswers');
  const questionText = document.getElementById('questionText');
  const answerContainer = document.getElementById('answerContainer');
  const explanationContainer = document.getElementById('explanationContainer');
  const explanationText = document.getElementById('explanationText');
  const progressFill = document.getElementById('progressFill');
  const prevBtn = document.getElementById('prevBtn');
  const nextBtn = document.getElementById('nextBtn');
  const checkBtn = document.getElementById('checkBtn');
  const submitBtn = document.getElementById('submitBtn');
  const completePracticeBtn = document.getElementById('completePracticeBtn');
  const countdown = document.getElementById('countdown');
  const resultsContainer = document.getElementById('resultsContainer');
  const resultsTitle = document.getElementById('resultsTitle');
  const finalScore = document.getElementById('finalScore');
  const finalCorrect = document.getElementById('finalCorrect');
  const finalTime = document.getElementById('finalTime');
  const finalRank = document.getElementById('finalRank');
  const timeStat = document.getElementById('timeStat');
  const rankStat = document.getElementById('rankStat');
  const experienceContainer = document.getElementById('experienceContainer');
  const chartsContainer = document.getElementById('chartsContainer');
  const reviewBtn = document.getElementById('reviewBtn');
  const nextPointBtn = document.getElementById('nextPointBtn');

  // ===== 初始化函数 =====
  function init() {
    console.log("初始化模式:", currentState.mode);
    console.log("知识点ID:", pointId);
    console.log("会话ID:", sessionId);
    console.log("题目数量:", currentState.quizData.questions.length);
    console.log("知识点信息:", currentState.quizData.pointInfo);

    // 设置页面标题
    document.title = isPractice ? '练习模式 - 渐进学习平台' : '正式闯关 - 渐进学习平台';

    // 关键修改：直接使用从Thymeleaf注入的题目数据
    if (currentState.quizData.questions && currentState.quizData.questions.length > 0) {
      totalQuestions.textContent = currentState.quizData.questions.length;

      // 初始化用户答案数组
      currentState.userAnswers = new Array(currentState.quizData.questions.length).fill(null);

      // 隐藏加载状态，显示答题界面
      loadingContainer.style.display = 'none';
      quizContent.style.display = 'block';

      // 显示第一题
      renderQuestion(0);

      // 正式模式启动计时器
      if (!isPractice) {
        startTimer();
      }
    } else {
      // 如果没有题目数据，显示错误信息
      showNoQuestionsMessage();
    }

    // 设置按钮事件
    setupButtonEvents();
  }

  // 显示错误信息
  function showError(title, message) {
    loadingContainer.style.display = 'none';
    errorTitle.textContent = title;
    errorMessage.textContent = message;
    errorContainer.style.display = 'block';
  }

  // 显示无题目信息
  function showNoQuestionsMessage() {
    loadingContainer.style.display = 'none';
    quizContent.innerHTML = `
      <div style="text-align: center; padding: 40px;">
        <div style="font-size: 48px; margin-bottom: 20px;">📝</div>
        <h3 style="color: #ffc107; margin-bottom: 15px;">暂无题目</h3>
        <p style="color: #666; margin-bottom: 20px;">该知识点暂无可用题目，请联系管理员添加。</p>
        <button onclick="history.back()" class="btn btn-outline">返回</button>
      </div>
    `;
    quizContent.style.display = 'block';
  }

  // ===== 题目渲染函数 =====
  function renderQuestion(index) {
    if (index < 0 || index >= currentState.quizData.questions.length) return;

    currentState.currentQuestion = index;
    currentQuestion.textContent = index + 1;

    // 更新进度条
    const progress = ((index + 1) / currentState.quizData.questions.length) * 100;
    progressFill.style.width = `${progress}%`;

    // 获取当前题目数据
    const question = currentState.quizData.questions[index];
    console.log("渲染题目:", question);

    // 设置题目文本
    questionText.textContent = question.content || '暂无题目内容';

    // 根据题目类型渲染不同的输入区域
    renderQuestionByType(question, index);

    // 更新按钮状态
    updateButtonStates();

    // 隐藏解析
    if (explanationContainer) {
      explanationContainer.style.display = 'none';
    }
    currentState.checked = false;

    // 显示/隐藏提交按钮
    if (submitBtn) {
      submitBtn.style.display = (index === currentState.quizData.questions.length - 1) ? 'inline-flex' : 'none';
    }
    if (completePracticeBtn) {
      completePracticeBtn.style.display = (index === currentState.quizData.questions.length - 1) ? 'inline-flex' : 'none';
    }

    // 更新正确题目数
    updateCorrectCount();
  }

  // 修改 renderQuestionByType 函数，在开头添加题型显示
  function renderQuestionByType(question, qIndex) {
    answerContainer.innerHTML = '';

    // 将数据库中的题目类型映射到前端支持的题目类型
    let questionType = question.questionType || 'single';

    // 类型映射
    const typeMapping = {
      'single_choice': 'single',
      'multiple_choice': 'multiple',
      'fill_blank': 'fill-blank',
      'true_false': 'single', // 判断题当作单选题处理
      'code': 'code',
      'essay': 'essay'
    };

    questionType = typeMapping[questionType] || questionType;

    console.log("题目类型:", questionType, "原始类型:", question.questionType);

    // 添加题型提示
    let typeHint = '';
    switch(questionType) {
      case 'single':
        typeHint = '📝 单选题（选择一个正确答案）';
        break;
      case 'multiple':
        typeHint = '📝 多选题（选择所有正确答案）';
        break;
      case 'fill-blank':
        typeHint = '📝 填空题（在输入框中填写答案）';
        break;
      case 'code':
        typeHint = '📝 编程题（在编辑器中编写代码）';
        break;
      case 'essay':
        typeHint = '📝 简答题（详细阐述你的观点）';
        break;
      default:
        typeHint = '📝 请回答以下问题';
    }

    const typeHintElement = document.createElement('div');
    typeHintElement.style.cssText = 'margin-bottom: 15px; color: #666; font-size: 14px; background: #f8f9fa; padding: 10px; border-radius: 6px; border-left: 4px solid #007bff;';
    typeHintElement.textContent = typeHint;
    answerContainer.appendChild(typeHintElement);

    // 根据题目类型渲染不同的输入区域
    switch (questionType) {
      case 'single':
        renderSingleChoice(question, qIndex);
        break;
      case 'multiple':
        renderMultipleChoice(question, qIndex);
        break;
      case 'fill-blank':
        renderFillBlank(question, qIndex);
        break;
      case 'code':
        renderCodeEditor(question, qIndex);
        break;
      case 'essay':
        renderEssayArea(question, qIndex);
        break;
      default:
        renderSingleChoice(question, qIndex);
    }
  }

  // 渲染单选题
  function renderSingleChoice(question, qIndex) {
    const optionsContainer = document.createElement('div');
    optionsContainer.className = 'options-container';

    let options = [];
    let optionLabels = ['A', 'B', 'C', 'D', 'E', 'F'];

    try {
      // 如果是判断题，设置固定选项
      if (question.questionType === 'true_false') {
        options = ['正确', '错误'];
        optionLabels = ['A', 'B'];
      } else {
        // 尝试解析选项JSON
        const optionsObj = JSON.parse(question.options || '{}');
        options = Object.values(optionsObj);
        console.log("单选题选项:", options);
      }
    } catch (e) {
      console.error('解析选项失败:', e);
      options = ['选项解析错误'];
    }

    options.forEach((option, index) => {
      const optionElement = document.createElement('div');
      optionElement.className = 'option-item';

      // 如果已选择此选项，添加selected类
      if (currentState.checked) {
        const correctAnswer = question.correctAnswer;
        let isCorrect = false;

        // 处理判断题
        if (question.questionType === 'true_false') {
          const correctOption = correctAnswer === 'true' ? '正确' : '错误';
          isCorrect = option === correctOption;
        } else {
          // 处理单选题
          const correctOption = options[correctAnswer.charCodeAt(0) - 65]; // A->0, B->1, etc.
          isCorrect = option === correctOption;
        }

        if (isCorrect) {
          optionElement.classList.add('correct');
        } else if (currentState.userAnswers[qIndex] === option && !isCorrect) {
          optionElement.classList.add('incorrect');
        }
      } else if (currentState.userAnswers[qIndex] === option) {
        optionElement.classList.add('selected');
      }

      optionElement.innerHTML = `
            <div class="option-label">${optionLabels[index]}</div>
            <div class="option-text">${option}</div>
        `;

      if (!currentState.checked) {
        optionElement.addEventListener('click', () => {
          selectSingleOption(qIndex, option);
        });
      }

      optionsContainer.appendChild(optionElement);
    });

    answerContainer.appendChild(optionsContainer);
  }

  // 修改 renderMultipleChoice 函数
  function renderMultipleChoice(question, qIndex) {
    const optionsContainer = document.createElement('div');
    optionsContainer.className = 'options-container';

    let options = [];
    let optionLabels = ['A', 'B', 'C', 'D', 'E', 'F'];

    try {
      // 尝试解析选项JSON
      let optionsData = question.options;

      if (typeof optionsData === 'string') {
        try {
          optionsData = JSON.parse(optionsData);
        } catch (e) {
          console.warn('JSON解析失败，尝试其他格式:', e);
          // 尝试逗号分隔格式
          options = parseCommaSeparatedOptions(optionsData);
        }
      }

      if (Array.isArray(optionsData)) {
        options = optionsData;
      } else if (typeof optionsData === 'object' && optionsData !== null) {
        // 如果是对象格式 {A: "内容", B: "内容"}
        options = Object.entries(optionsData).map(([key, value]) => {
          return `${key}. ${value}`;
        });
      }

      console.log("多选题选项:", options);
    } catch (e) {
      console.error('解析选项失败:', e);
      options = ['选项解析错误'];
    }

    let correctAnswers = [];
    try {
      // 多选题正确答案是逗号分隔的字母，如 "B,C,D"
      const correctLetters = question.correctAnswer.split(',').map(item => item.trim());
      correctAnswers = correctLetters.map(letter => {
        const index = letter.charCodeAt(0) - 65; // A->0, B->1, etc.
        return options[index];
      });
    } catch (e) {
      console.error('解析正确答案失败:', e);
    }

    options.forEach((option, index) => {
      const optionElement = document.createElement('div');
      optionElement.className = 'option-item';

      // 如果已检查答案
      if (currentState.checked) {
        if (correctAnswers.includes(option)) {
          optionElement.classList.add('correct');
        } else if (currentState.userAnswers[qIndex] &&
                currentState.userAnswers[qIndex].includes(option) &&
                !correctAnswers.includes(option)) {
          optionElement.classList.add('incorrect');
        }
      } else if (currentState.userAnswers[qIndex] &&
              currentState.userAnswers[qIndex].includes(option)) {
        optionElement.classList.add('selected');
      }

      optionElement.innerHTML = `
      <div class="option-label">${optionLabels[index]}</div>
      <div class="option-text">${option}</div>
    `;

      if (!currentState.checked) {
        optionElement.addEventListener('click', () => {
          selectMultipleOption(qIndex, option);
        });
      }

      optionsContainer.appendChild(optionElement);
    });

    answerContainer.appendChild(optionsContainer);
  }

  // 在练习页面的脚本中添加这个函数
  function parseCommaSeparatedOptions(optionsString) {
    console.log('开始解析逗号分隔选项:', optionsString);

    if (!optionsString || typeof optionsString !== 'string') {
      return [];
    }

    // 清理字符串：移除多余空格和引号
    const cleanString = optionsString.trim().replace(/^"+|"+$/g, '');

    // 按逗号分割，并过滤空值
    const options = cleanString.split(',').map(opt => opt.trim()).filter(opt => opt.length > 0);

    console.log('逗号分隔解析结果:', options);
    return options;
  }

  // 渲染填空题
  function renderFillBlank(question, qIndex) {
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'fill-blank-input';
    input.placeholder = '请输入答案';

    // 如果已有答案，填充答案
    if (currentState.userAnswers[qIndex]) {
      input.value = currentState.userAnswers[qIndex];
    }

    if (!currentState.checked) {
      input.addEventListener('input', () => {
        currentState.userAnswers[qIndex] = input.value;
      });
    } else {
      input.disabled = true;

      // 显示正确答案
      const correctAnswer = question.correctAnswer;
      if (currentState.userAnswers[qIndex] &&
              currentState.userAnswers[qIndex].toLowerCase().trim() ===
              correctAnswer.toLowerCase().trim()) {
        input.style.borderColor = '#28a745';
        input.style.backgroundColor = 'rgba(40, 167, 69, 0.1)';
      } else {
        input.style.borderColor = '#dc3545';
        input.style.backgroundColor = 'rgba(220, 53, 69, 0.1)';

        // 显示正确答案
        const correctAnswerElement = document.createElement('div');
        correctAnswerElement.style.marginTop = '10px';
        correctAnswerElement.style.color = '#28a745';
        correctAnswerElement.innerHTML = `<strong>正确答案:</strong> ${correctAnswer}`;
        answerContainer.appendChild(correctAnswerElement);
      }
    }

    answerContainer.appendChild(input);
  }

  // 渲染代码编辑器
  function renderCodeEditor(question, qIndex) {
    const textarea = document.createElement('textarea');
    textarea.className = 'code-editor';
    textarea.placeholder = '请在此编写你的代码...';

    // 如果已有答案，填充答案
    if (currentState.userAnswers[qIndex]) {
      textarea.value = currentState.userAnswers[qIndex];
    }

    if (!currentState.checked) {
      textarea.addEventListener('input', () => {
        currentState.userAnswers[qIndex] = textarea.value;
      });
    } else {
      textarea.disabled = true;

      // 显示参考答案
      const referenceAnswer = document.createElement('div');
      referenceAnswer.style.marginTop = '10px';
      referenceAnswer.style.color = '#007bff';
      referenceAnswer.innerHTML = `<strong>参考答案:</strong><pre style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-top: 5px;">${question.correctAnswer || '暂无参考答案'}</pre>`;
      answerContainer.appendChild(referenceAnswer);
    }

    answerContainer.appendChild(textarea);
  }

  // 渲染简答题区域
  function renderEssayArea(question, qIndex) {
    const textarea = document.createElement('textarea');
    textarea.className = 'essay-textarea';
    textarea.placeholder = '请在此输入你的答案...';

    // 如果已有答案，填充答案
    if (currentState.userAnswers[qIndex]) {
      textarea.value = currentState.userAnswers[qIndex];
    }

    if (!currentState.checked) {
      textarea.addEventListener('input', () => {
        currentState.userAnswers[qIndex] = textarea.value;
      });
    } else {
      textarea.disabled = true;
    }

    answerContainer.appendChild(textarea);
  }

  // ===== 答题逻辑函数 =====
  function selectSingleOption(qIndex, option) {
    currentState.userAnswers[qIndex] = option;
    renderQuestion(qIndex);
  }

  // 确保 selectMultipleOption 函数正确工作
  function selectMultipleOption(qIndex, option) {
    if (!currentState.userAnswers[qIndex]) {
      currentState.userAnswers[qIndex] = [];
    }

    const answerIndex = currentState.userAnswers[qIndex].indexOf(option);
    if (answerIndex === -1) {
      currentState.userAnswers[qIndex].push(option);
    } else {
      currentState.userAnswers[qIndex].splice(answerIndex, 1);
    }

    renderQuestion(qIndex);
  }

  // 检查答案（练习模式专用）
  function checkAnswer() {
    currentState.checked = true;

    // 显示解析
    const question = currentState.quizData.questions[currentState.currentQuestion];
    explanationText.innerHTML = question.explanation || '暂无解析';
    if (explanationContainer) {
      explanationContainer.style.display = 'block';
    }

    // 重新渲染当前题目以显示正确/错误状态
    renderQuestion(currentState.currentQuestion);

    // 更新正确题目数
    updateCorrectCount();
  }

  // 更新正确题目数
  function updateCorrectCount() {
    let correctCount = 0;

    currentState.quizData.questions.forEach((question, index) => {
      if (currentState.userAnswers[index] !== null && currentState.userAnswers[index] !== '') {
        const questionType = question.questionType || 'single';
        const userAnswer = currentState.userAnswers[index];
        const correctAnswer = question.correctAnswer;

        switch (questionType) {
          case 'single':
            if (userAnswer === correctAnswer) {
              correctCount++;
            }
            break;
          case 'multiple':
            try {
              const correctAnswers = JSON.parse(correctAnswer || '[]');
              const userAnswers = Array.isArray(userAnswer) ? userAnswer : [userAnswer];
              if (JSON.stringify(userAnswers.sort()) === JSON.stringify(correctAnswers.sort())) {
                correctCount++;
              }
            } catch (e) {
              console.error('多选题答案比较错误:', e);
            }
            break;
          case 'fill-blank':
            if (userAnswer && userAnswer.toLowerCase().trim() === correctAnswer.toLowerCase().trim()) {
              correctCount++;
            }
            break;
          case 'code':
          case 'essay':
            // 代码题和简答题只要有答案就算正确（简化处理）
            if (userAnswer && userAnswer.trim() !== '') {
              correctCount++;
            }
            break;
        }
      }
    });

    correctAnswers.textContent = correctCount;
  }

  // 更新按钮状态
  function updateButtonStates() {
    prevBtn.disabled = currentState.currentQuestion === 0;
    nextBtn.disabled = currentState.currentQuestion === currentState.quizData.questions.length - 1;
  }

  // ===== 计时器函数（正式闯关模式专用） =====
  function startTimer() {
    if (!isPractice) {
      currentState.timer = setInterval(() => {
        currentState.timeLeft--;

        if (currentState.timeLeft <= 0) {
          clearInterval(currentState.timer);
          submitQuiz();
          return;
        }

        updateTimerDisplay();

        // 最后5分钟变红
        if (currentState.timeLeft <= 300) {
          countdown.style.color = '#dc3545';
        }
      }, 1000);
    }
  }

  function updateTimerDisplay() {
    const minutes = Math.floor(currentState.timeLeft / 60);
    const seconds = currentState.timeLeft % 60;
    countdown.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }

  // ===== 提交测验函数 =====
  async function submitQuiz() {
    // 停止计时器
    if (currentState.timer) {
      clearInterval(currentState.timer);
    }

    // 计算得分
    let totalScore = 0;
    let earnedScore = 0;
    let correctCount = 0;

    currentState.quizData.questions.forEach((question, index) => {
      const questionScore = question.score || 20; // 默认20分
      totalScore += questionScore;

      const questionType = question.questionType || 'single';
      const userAnswer = currentState.userAnswers[index];
      const correctAnswer = question.correctAnswer;

      let isCorrect = false;

      switch (questionType) {
        case 'single':
          if (userAnswer === correctAnswer) {
            earnedScore += questionScore;
            correctCount++;
            isCorrect = true;
          }
          break;
        case 'multiple':
          try {
            const correctAnswers = JSON.parse(correctAnswer || '[]');
            const userAnswers = Array.isArray(userAnswer) ? userAnswer : [userAnswer];
            if (JSON.stringify(userAnswers.sort()) === JSON.stringify(correctAnswers.sort())) {
              earnedScore += questionScore;
              correctCount++;
              isCorrect = true;
            }
          } catch (e) {
            console.error('多选题评分错误:', e);
          }
          break;
        case 'fill-blank':
          if (userAnswer && userAnswer.toLowerCase().trim() === correctAnswer.toLowerCase().trim()) {
            earnedScore += questionScore;
            correctCount++;
            isCorrect = true;
          }
          break;
        case 'code':
        case 'essay':
          // 代码题和简答题 - 只要有答案就给一半分数
          if (userAnswer && userAnswer.trim() !== '') {
            earnedScore += questionScore * 0.5;
            correctCount++;
            isCorrect = true;
          }
          break;
      }
    });

    // 计算百分比
    const scorePercentage = Math.round((earnedScore / totalScore) * 100);

    // 更新结果统计
    finalScore.textContent = scorePercentage;
    finalCorrect.textContent = `${correctCount}/${currentState.quizData.questions.length}`;

    // 如果是闯关模式，显示时间和排位
    if (!isPractice) {
      const timeUsed = 15 * 60 - currentState.timeLeft;
      const minutes = Math.floor(timeUsed / 60);
      const seconds = timeUsed % 60;
      finalTime.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

      // 确定排位
      let rank = "青铜III";
      if (scorePercentage >= 90) rank = "王者";
      else if (scorePercentage >= 80) rank = "钻石";
      else if (scorePercentage >= 70) rank = "黄金";
      else if (scorePercentage >= 60) rank = "白银";

      finalRank.textContent = rank;
      timeStat.style.display = 'block';
      rankStat.style.display = 'block';
      resultsTitle.textContent = '闯关结果';

      // 显示经验成长和图表
      experienceContainer.style.display = 'block';
      chartsContainer.style.display = 'grid';

      // 更新用户数据
      await updateUserDataAfterQuiz(scorePercentage, correctCount);

      // 初始化图表
      initCharts();
    } else {
      resultsTitle.textContent = '练习完成';
    }

    // 提交结果到后端
    await submitResultsToBackend(scorePercentage, correctCount, currentState.quizData.questions.length);

    // 隐藏答题区域，显示结果区域
    document.getElementById('quiz-container').style.display = 'none';
    resultsContainer.style.display = 'block';
  }

  // 提交结果到后端
  async function submitResultsToBackend(score, correctAnswers, totalQuestions) {
    try {
      const response = await fetch('/practice/gateway/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `sessionId=${sessionId}&pointId=${pointId}&score=${score}&totalQuestions=${totalQuestions}&correctAnswers=${correctAnswers}&isPractice=${isPractice}`
      });

      const result = await response.json();
      console.log('提交结果:', result);

      if (!result.success) {
        console.error('提交结果失败:', result.message);
      }
    } catch (error) {
      console.error('提交结果时发生错误:', error);
    }
  }

  // 测验后更新用户数据（正式闯关模式专用）
  async function updateUserDataAfterQuiz(scorePercentage, correctCount) {
    try {
      const response = await fetch(`/api/user/stats?pointId=${pointId}`);
      const result = await response.json();

      if (result.success) {
        currentState.userData = result.data;
        updateUserStatsUI();
      } else {
        console.error('获取用户数据失败:', result.message);
        // 使用模拟数据作为后备
        useFallbackUserData(scorePercentage);
      }
    } catch (error) {
      console.error('获取用户数据时发生错误:', error);
      // 使用模拟数据作为后备
      useFallbackUserData(scorePercentage);
    }
  }

  // 使用后备用户数据
  function useFallbackUserData(scorePercentage) {
    // 模拟用户数据更新
    currentState.userData.level = 5;
    currentState.userData.currentExp = 650 + Math.round(scorePercentage / 10);
    currentState.userData.nextLevelExp = 1000;
    currentState.userData.practiceCount = 12;
    currentState.userData.challengeCount = 8;
    currentState.userData.averageScore = 82;
    currentState.userData.mastery = {
      "Spring基础": 85,
      "Spring MVC": 78,
      "Spring Boot": 90,
      "Spring Security": 65,
      "Spring Data": 72
    };

    updateUserStatsUI();
  }

  // 更新用户统计UI
  function updateUserStatsUI() {
    document.getElementById('userLevel').textContent = currentState.userData.level;
    document.getElementById('currentExp').textContent = currentState.userData.currentExp;
    document.getElementById('nextLevelExp').textContent = currentState.userData.nextLevelExp;

    const expPercentage = (currentState.userData.currentExp / currentState.userData.nextLevelExp) * 100;
    document.getElementById('experienceFill').style.width = `${expPercentage}%`;
  }

  // ===== 图表函数（正式闯关模式专用） =====
  function initCharts() {
    // 知识点掌握情况图表
    const masteryCtx = document.getElementById('masteryChart').getContext('2d');
    const masteryLabels = Object.keys(currentState.userData.mastery);
    const masteryData = Object.values(currentState.userData.mastery);

    new Chart(masteryCtx, {
      type: 'bar',
      data: {
        labels: masteryLabels,
        datasets: [{
          label: '掌握度(%)',
          data: masteryData,
          backgroundColor: [
            'rgba(255, 99, 132, 0.7)',
            'rgba(54, 162, 235, 0.7)',
            'rgba(255, 206, 86, 0.7)',
            'rgba(75, 192, 192, 0.7)',
            'rgba(153, 102, 255, 0.7)'
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            beginAtZero: true,
            max: 100
          }
        }
      }
    });

    // 训练次数统计图表
    const trainingCtx = document.getElementById('trainingChart').getContext('2d');
    new Chart(trainingCtx, {
      type: 'doughnut',
      data: {
        labels: ['练习模式', '闯关模式'],
        datasets: [{
          data: [currentState.userData.practiceCount, currentState.userData.challengeCount],
          backgroundColor: [
            'rgba(54, 162, 235, 0.7)',
            'rgba(255, 99, 132, 0.7)'
          ],
          borderColor: [
            'rgba(54, 162, 235, 1)',
            'rgba(255, 99, 132, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        responsive: true
      }
    });
  }

  // ===== 按钮事件设置 =====
  function setupButtonEvents() {
    // 上一题按钮
    prevBtn.addEventListener('click', () => {
      if (currentState.currentQuestion > 0) {
        renderQuestion(currentState.currentQuestion - 1);
      }
    });

    // 下一题按钮
    nextBtn.addEventListener('click', () => {
      if (currentState.currentQuestion < currentState.quizData.questions.length - 1) {
        renderQuestion(currentState.currentQuestion + 1);
      }
    });

    // 检查答案按钮（练习模式）
    if (checkBtn) {
      checkBtn.addEventListener('click', () => {
        checkAnswer();
      });
    }

    // 提交按钮（正式闯关模式）
    if (submitBtn) {
      submitBtn.addEventListener('click', () => {
        submitQuiz();
      });
    }

    // 完成练习按钮（练习模式）
    if (completePracticeBtn) {
      completePracticeBtn.addEventListener('click', () => {
        submitQuiz();
      });
    }

    // 查看解析按钮（练习模式）
    if (reviewBtn) {
      reviewBtn.addEventListener('click', () => {
        // 显示所有题目的解析
        currentState.checked = true;
        renderQuestion(currentState.currentQuestion);
      });
    }

    // 下一个知识点按钮
    nextPointBtn.addEventListener('click', () => {
      if (isPractice) {
        // 练习模式：跳转到正式闯关
        window.location.href = `/practice/gateway/formal?pointId=${pointId}`;
      } else {
        // 正式闯关：进入下一个知识点
        alert('进入下一个知识点');
        // 在实际应用中，这里会跳转到下一个知识点
      }
    });

    // 重试按钮
    retryBtn.addEventListener('click', () => {
      errorContainer.style.display = 'none';
      loadingContainer.style.display = 'block';
      // 重新加载页面
      location.reload();
    });
  }

  // ===== 页面加载完成后初始化 =====
  document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>